import os, time, shutil, sys, subprocess, smtplib

mail_format ='''\
Subject: %s

%s'''

def SendLog(log_list):
    from_address = 'hantempo@gmail.com'
    to_address = ['Tempo.han@autodesk.com']
    subject = 'Copy Maya Install Log'
    content = mail_format % (subject, '\n'.join(log_list))

    try:
        server = smtplib.SMTP('smtp.gmail.com:587')
        server.starttls()
        server.login(os.environ['GMAIL_USER'], os.environ['GMAIL_PASSWORD'])
        server.sendmail(from_address, to_address, content)
    finally:
        server.quit()

if __name__ == '__main__':
    environ_variables = ('GMAIL_USER', 'GMAIL_PASSWORD', 'DOMAIN_USER', 'DOMAIN_PASSWORD')
    for v in environ_variables:
        if not v in os.environ:
            print('Undefined environment variable %s' % v)
            sys.exit(1)

    server_path = '//shaaspera01/tordist/Maya/2012/Mainline'
    mount_path = '/home/hant/remote/maya_install'
    log = []
    
    # Check mount path
    if os.access(mount_path, os.F_OK|os.W_OK):
        log.append('Mount path %s already exists.' % mount_path)
    else:
        try:
            os.makedirs(mount_path)
        except OSError:
            log.append('Failed to create mount path %s.' % mount_path)
            SendLog(log)
            sys.exit(1)
        log.append('Create mount path %s.' % mount_path)

    # Mount toronto server if need
    if len(os.listdir(mount_path)) != 0:
        log.append('Toronto server %s already mounted.' % server_path)
    else:
        options = 'username=%s,password=%s' % (os.environ['DOMAIN_USER'], os.environ['DOMAIN_PASSWORD'])
        mount_cmd = ' '.join(['mount -t cifs -o', options, server_path, mount_path])
        mount_cmd_tokens = mount_cmd.split()
        p = subprocess.Popen(mount_cmd_tokens, stderr = subprocess.PIPE)
        error_string = p.stderr.read().rstrip()
        p.communicate()
        log.append('Command: ' + mount_cmd)
        
        if p.returncode:
            log.append(error_string)
            log.append('Failed to mount toronto server %s.' % server_path)
            SendLog(log)
            sys.exit(1)
        else:
            log.append('Mount toronto server %s.' % server_path)

    dest_base = '/home/hant/maya_install'
    subfolder_list = ('linux-amd64', 'win-amd64')
    for subfolder in subfolder_list:
        src_folder = os.path.join(mount_path, subfolder)
        dest_folder = os.path.join(dest_base, subfolder)
        if not os.path.exists(dest_folder):
            os.makedirs(dest_folder)

        date_folders = os.listdir(src_folder)
        for folder in date_folders:
            src_abs = os.path.join(src_folder, folder)
            dest_abs = os.path.join(dest_folder, folder)
            elapse_days = time.localtime(time.time() - os.path.getmtime(src_abs)).tm_mday
            if elapse_days < 3 and not os.path.exists(dest_abs):
                shutil.copytree(src_abs, dest_abs)
                log.append('Copy folder from %s to %s.' % (src_abs, dest_abs))

    SendLog(log)
